/**
 * iscroll extension using with jqm
 * @author Levin
 * @version 1.0
 */
JF.M("iscroll",(function($,S){

	var p={},pub={};

	p.iscroll={
		get:function(id){
			var j=this.cache.length;
			for(var i=j-1;i>=0;i--){
				if(this.cache[i].key===id){
					return this.cache[i];
				};
			};
			return null;
		},
		cache:[],
		setup:function(){
			var me=this;
			$(":jqmData(role='page')").live("pageshow",function(){

				var $items=$(this).find(":jqmData(iscroll='true')");
				if($items.length==0) return;

				$items.each(function(i,o){
					var $i=$(this),
						id=this.id||("is-"+JF.RdStr(6));

					if(me.get(id)) return;

					if(!this.id){
						$i.attr("id",id);
					};

					var cfg=$i.jqmData("iscroll-cfg");
					
					if(cfg&&cfg.onPullUp){
						cfg.onPullUp_key=cfg.onPullUp;
						cfg.onPullUp=function(){
							//TODO:use global function to decouple!
							JF.ajaxPool[cfg.onPullUp_key].load($i,function($obj,data){
								setTimeout(function(){
									me.get($obj[0].id).val.refresh();
									$obj.children(":eq(0)").append($obj.find('.iScrollPullUp'));
								},0);
								
							});
						};
					};

					if(cfg&&cfg.onScrollEnd){
						cfg.onScrollEnd_key=cfg.onScrollEnd;
						cfg.onScrollEnd=function(){
							eval('('+cfg.onScrollEnd_key+')').call(this,{target:$i});
						};
					};
					
					me.cache.push({
						key:this.id,
						val:new S(this.id,cfg)
					});				
				});
			});

			//homepage iscroll
			/*
			me.cache.push({
				key:'page_1_scroll',
				val:new S('page_1_scroll')
			});
			*/
			

		},
		teardown:function(){
			for(var i=this.cache.length-1;i>=0;i--){
				this.cache[i].val.destroy();
			};
			this.cache.length=0;
		}
	};

	pub.onLoad=function(){
		p.iscroll.setup();
	};
	return pub;

})(jQuery,iScroll));